package com.lynn.springboot_demo.config;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author cl
 * @Date 2020/9/8 15:17
 * aop 切面层 实现controller层日志切面
 */

@Aspect
@Component
public class WebLogAspectConfig {

    private static final Logger log = LoggerFactory.getLogger(WebLogAspectConfig.class);

    /**
     * 定义切入点，切入点是com.lynn.springboot_demo.controller包下所有类的所有方法
     */
    @Pointcut("execution(public * com.lynn.springboot_demo.controller..*.*(..))")
    public void webLog() {
    }

    /**
     * 前置通知：在连接点之前执行的通知,方法调用前被调用
     *
     * @param joinPoint
     * @throws Throwable
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        //接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //记录下请求内容
        log.info("请求URI:" + request.getRequestURL().toString());
        log.info("请求方式:" + request.getMethod());
        log.info("IP:" + request.getRemoteAddr());
        log.info("方法:" + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("参数:" + Arrays.toString(joinPoint.getArgs()));
    }

    /**
     * 后置通知，处理完业务逻辑之后的通知
     *
     * @param result
     * @throws Throwable
     */
    @AfterReturning(returning = "result", pointcut = "webLog()")
    public void doAfterReturning(Object result) throws Throwable {
        //处理完请求返回内容
        log.info("请求返回数据:" + result);
    }



}
